package com.huluobo.day11_im.contact.prensenter;

import android.util.Log;

import com.huluobo.day11_im.bean.ContactListItemBean;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMClient;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ContactPresenter implements ContactContract.Presenter {
    private ContactContract.View view;

    public ContactPresenter(ContactContract.View view) {
        this.view = view;
    }

    @Override
    public void loadContacts() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                EMClient.getInstance().contactManager().aysncGetAllContactsFromServer(new EMValueCallBack<List<String>>() {
                    @Override
                    public void onSuccess(List<String> usernames) {
                        List<ContactListItemBean> contactListItemBeans = new ArrayList<>();
                        Collections.sort(usernames);
                        for (int i = 0; i < usernames.size(); i++) {
                            boolean showFirstLetter = false;
                            if (i == 0 || usernames.get(i).charAt(0) != usernames.get(i - 1).charAt(0)) {
                                showFirstLetter = true;
                            }
                            ContactListItemBean contactListItemBean =
                                    new ContactListItemBean(usernames.get(i),
                                            Character.toUpperCase(usernames.get(i).charAt(0)),
                                            showFirstLetter);
                            contactListItemBeans.add(contactListItemBean);
                        }
                        view.loadContactsSuccess(contactListItemBeans);
                    }

                    @Override
                    public void onError(int error, String errorMsg) {
                        view.loadContactsFailed(errorMsg);
                    }
                });
            }
        }).start();
    }
}
